package cn.cheniy.swiftmark.common.rocketmq.config;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.spring.autoconfigure.RocketMQAutoConfiguration;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * @author cheniy
 * @description 设置mq的配置
 *  
 */
@RefreshScope
@Configuration
@Import ({RocketMQAutoConfiguration.class})
public class RocketMqAdapter {

    @Autowired
    private RocketMQMessageConverter rocketMqMessageConverter;

    @Value ("${rocketmq.name-server:}")
    private String nameServer;

    /**
     * 代替配置文件配置，创建并配置RocketMQTemplate实例
     * @param topic
     * @return
     */
    public RocketMQTemplate getTemplateByTopicName(String topic){
        RocketMQTemplate mqTemplate = new RocketMQTemplate();
        // 创建一个默认的消息生产者，以传入的主题名称作为生产者组名
        DefaultMQProducer producer = new DefaultMQProducer(topic);
        producer.setNamesrvAddr(nameServer);
        // 设置消息发送失败时的重试次数为2次
        producer.setRetryTimesWhenSendFailed(2);
        producer.setSendMsgTimeout((int) RocketMqConstant.TIMEOUT);
        mqTemplate.setProducer(producer);
        // 设置消息转换器，用于将Java对象转换为RocketMQ可以处理的消息格式
        mqTemplate.setMessageConverter(rocketMqMessageConverter.getMessageConverter());
        return mqTemplate;
    }

}

/** 使用
 * @Service
 * public class MessageSenderService {
 *
 *     @Autowired
 *     private RocketMqAdapter rocketMqAdapter;
 *
 *     public void sendMessageToTopic(String topic, String message) {
 *         @根据主题名称获取配置好的RocketMQTemplate实例
 *         RocketMQTemplate mqTemplate = rocketMqAdapter.getTemplateByTopicName(topic);
 *         // 使用RocketMQTemplate实例向指定主题发送消息
 *         mqTemplate.convertAndSend(topic, message);
 *     }
 * }
 */
